package com.bdqn.springbootmybatisplus.web;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 过滤器 拦截未授权的请求
 *
 * @author LILIBO
 * @since 2021-11-29
 */
public class AuthorizationFilter implements Filter {

    /**
     * 初始化
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 执行过滤（在执行Servlet之前）
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest HttpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (HttpRequest.getSession().getAttribute("loginUser") == null) {
            httpResponse.setContentType("text/html;charset=UTF-8");
            PrintWriter out = httpResponse.getWriter();
            out.print("<script>alert('请先登陆，再进行后续操作！(Filter 控制)');location.href='" + HttpRequest.getContextPath() + "/login.jsp';</script>");
        } else {
            // 完成本次过滤器，执行下一个过滤器（没有的话，执行Servlet）
            chain.doFilter(request, response);
        }
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
    }
}
